<template>
  <div class="lov-config-page">
    <div class="page-header">
      <h2>LOV 配置管理</h2>
      <el-button type="primary" icon="Plus" @click="handleAdd">新建配置</el-button>
    </div>

    <!-- 配置列表 -->
    <el-table :data="configList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="lovCode" label="代码" width="200" />
      <el-table-column prop="lovName" label="名称" width="150" />
      <el-table-column prop="lovDesc" label="描述" />
      <el-table-column prop="dataSourceType" label="类型" width="80" />
      <el-table-column prop="enabled" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.enabled ? 'success' : 'danger'">
            {{ row.enabled ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 配置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" label-width="120px" ref="formRef" :rules="rules">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="代码" prop="lovCode">
                  <el-input v-model="form.lovCode" placeholder="LOV_STUDENT_DYNAMIC" :disabled="isEdit" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="名称" prop="lovName">
                  <el-input v-model="form.lovName" placeholder="学生查询(动态SQL)" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="描述" prop="lovDesc">
              <el-input v-model="form.lovDesc" placeholder="支持年龄范围和姓名关键词的动态查询" />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="弹窗标题" prop="title">
                  <el-input v-model="form.title" placeholder="LOV" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="数据源类型" prop="dataSourceType">
                  <el-select v-model="form.dataSourceType" style="width: 100%">
                    <el-option label="自定义SQL" value="SQL" />
                    <el-option label="URL请求" value="URL" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="自定义SQL" prop="dataSourceSql" v-if="form.dataSourceType === 'SQL'">
              <el-input
                type="textarea"
                v-model="form.dataSourceSql"
                placeholder="SELECT stu_id, stu_name, stu_age FROM student&#10;<where>&#10;  <if test=&quot;minAge != null&quot;>&#10;    AND stu_age >= #{minAge}&#10;  </if>&#10;</where>"
                :rows="6"
              />
              <div style="margin-top: 5px; font-size: 12px; color: #909399;">
                💡 提示：无需手动添加&lt;script&gt;标签，后端会自动处理。支持MyBatis动态SQL（&lt;if&gt;、&lt;where&gt;等标签）
              </div>
            </el-form-item>

            <el-form-item label="数据源URL" prop="dataSourceUrl" v-if="form.dataSourceType === 'URL'">
              <el-input v-model="form.dataSourceUrl" placeholder="http://api.example.com/data" />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="值字段" prop="valueField">
                  <el-input v-model="form.valueField" placeholder="stu_id" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="显示字段" prop="displayField">
                  <el-input v-model="form.displayField" placeholder="stu_name" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="页大小" prop="pageSize">
                  <el-input-number v-model="form.pageSize" :min="5" :max="100" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="弹窗高度" prop="dialogHeight">
                  <el-input-number v-model="form.dialogHeight" :min="200" :max="800" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="弹窗宽度" prop="dialogWidth">
                  <el-input-number v-model="form.dialogWidth" :min="400" :max="1200" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="是否启用">
                  <el-switch v-model="form.enabled" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="列配置" name="columns">
            <div class="column-config-header">
              <el-button type="primary" icon="Plus" size="small" @click="handleAddColumn">添加列</el-button>
            </div>
            <el-table :data="form.columns" border style="width: 100%">
              <el-table-column label="显示名称" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.displayName" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="字段名" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.fieldName" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="列宽" width="100">
                <template #default="{ row }">
                  <el-input-number v-model="row.columnWidth" size="small" :min="50" />
                </template>
              </el-table-column>
              <el-table-column label="表格可见" width="90">
                <template #default="{ row }">
                  <el-switch v-model="row.visible" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="可查询" width="90">
                <template #default="{ row }">
                  <el-switch v-model="row.queryable" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="列序号" width="100">
                <template #default="{ row }">
                  <el-input-number v-model="row.columnOrder" size="small" :min="0" />
                </template>
              </el-table-column>
              <el-table-column label="查询顺序" width="100">
                <template #default="{ row }">
                  <el-input-number v-model="row.queryOrder" size="small" :min="0" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template #default="{ $index }">
                  <el-button link type="danger" size="small" @click="handleDeleteColumn($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

interface LovColumnConfig {
  displayName: string
  fieldName: string
  columnWidth: number
  visible: boolean
  queryable: boolean
  columnOrder: number
  queryOrder: number
}

interface LovConfig {
  id?: number
  lovCode: string
  lovName: string
  lovDesc: string
  title: string
  dataSourceSql: string
  dataSourceType: string
  dataSourceUrl: string
  displayField: string
  valueField: string
  pageSize: number
  dialogHeight: number
  dialogWidth: number
  enabled: boolean
  columns: LovColumnConfig[]
}

const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新建LOV配置')
const isEdit = ref(false)
const activeTab = ref('basic')
const formRef = ref()
const configList = ref<LovConfig[]>([])

const form = reactive<LovConfig>({
  lovCode: '',
  lovName: '',
  lovDesc: '',
  title: 'LOV',
  dataSourceSql: '',
  dataSourceType: 'SQL',
  dataSourceUrl: '',
  displayField: '',
  valueField: '',
  pageSize: 10,
  dialogHeight: 400,
  dialogWidth: 700,
  enabled: true,
  columns: []
})

const rules = {
  lovCode: [{ required: true, message: '请输入LOV代码', trigger: 'blur' }],
  lovName: [{ required: true, message: '请输入LOV名称', trigger: 'blur' }],
  dataSourceSql: [{ required: true, message: '请输入SQL语句', trigger: 'blur' }],
  valueField: [{ required: true, message: '请输入值字段', trigger: 'blur' }],
  displayField: [{ required: true, message: '请输入显示字段', trigger: 'blur' }],
}

// 加载配置列表
async function loadConfigList() {
  loading.value = true
  try {
    const response = await request.get('/lov/configs')
    configList.value = response.data || []
  } catch (error) {
    console.error('加载配置列表失败:', error)
    ElMessage.error('加载配置列表失败')
  } finally {
    loading.value = false
  }
}

// 新建
function handleAdd() {
  isEdit.value = false
  dialogTitle.value = '新建LOV配置'
  resetForm()
  dialogVisible.value = true
}

// 编辑
function handleEdit(row: LovConfig) {
  isEdit.value = true
  dialogTitle.value = '编辑LOV配置'

  // 直接使用列表中的数据（后端已经包含了列配置）
  Object.assign(form, row)
  if (!form.columns) {
    form.columns = []
  }

  dialogVisible.value = true
  activeTab.value = 'basic'
}

// 删除
function handleDelete(row: LovConfig) {
  ElMessageBox.confirm('确定要删除该配置吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await request.delete(`/lov/config/${row.id}`)
      ElMessage.success('删除成功')
      loadConfigList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 保存
async function handleSave() {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    saving.value = true
    try {
      if (isEdit.value) {
        await request.put('/lov/config', form)
        ElMessage.success('更新成功')
      } else {
        await request.post('/lov/config', form)
        ElMessage.success('创建成功')
      }
      dialogVisible.value = false
      loadConfigList()
    } catch (error) {
      console.error('保存失败:', error)
      ElMessage.error('保存失败')
    } finally {
      saving.value = false
    }
  })
}

// 添加列
function handleAddColumn() {
  form.columns.push({
    displayName: '',
    fieldName: '',
    columnWidth: 150,
    visible: true,
    queryable: false,
    columnOrder: form.columns.length,
    queryOrder: form.columns.length
  })
}

// 删除列
function handleDeleteColumn(index: number) {
  form.columns.splice(index, 1)
}

// 重置表单
function resetForm() {
  form.lovCode = ''
  form.lovName = ''
  form.lovDesc = ''
  form.title = 'LOV'
  form.dataSourceSql = ''
  form.dataSourceType = 'SQL'
  form.dataSourceUrl = ''
  form.displayField = ''
  form.valueField = ''
  form.pageSize = 10
  form.dialogHeight = 400
  form.dialogWidth = 700
  form.enabled = true
  form.columns = []
  activeTab.value = 'basic'
}

onMounted(() => {
  loadConfigList()
})
</script>

<style scoped>
.lov-config-page {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-header h2 {
  margin: 0;
}
.column-config-header {
  margin-bottom: 10px;
}
</style>
